package com.suixuan.support.web.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.suixuan.support.util.ConstantUtils;

/**
 * Nanjing Zhou Su co.,Ltd
 * 
 * @Title: NoCacheInterceptor.java
 * @Package: com.suixuan
 * @Description: 处理重复提交的拦截器
 * @Author: suixuan
 * @Date 2010-3-31 上午10:46:31
 * @Version V1.0
 */
public class NoCacheInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String currUrl = request.getRequestURL().toString();
		// 如果当前Url与配置的拦截的Url不匹配，则不进行拦截，执行正常流程

		// 设置匹配标识
		boolean flag = false;
		for (String patternUrl : interceptorUrl) {
			if (matches(currUrl, patternUrl)) {

				// 有匹配退出
				flag = true;
				break;
			}

		}
		// 无匹配执行原流程
		if (!flag) {
			return super.preHandle(request, response, handler);
		}

		HttpSession session = request.getSession();

		String tokenValue = (String) session.getAttribute(ConstantUtils.TOKEN_VALUE);

		if (!StringUtils.hasText(tokenValue)) {
			// 生成新的token
			session.setAttribute(ConstantUtils.TOKEN_VALUE,
					session.getId() + String.valueOf(System.currentTimeMillis()));

			return super.preHandle(request, response, handler);
		} else {
			// 判断是否重复提交（如果session中的token值与request中的token值不一致则判定重复提交）
			String requestToken = (String) request.getParameter(ConstantUtils.TOKEN_VALUE);
			// 请求中不包含requestToken，非Form提交
			if (!StringUtils.hasText(requestToken)) {
				return super.preHandle(request, response, handler);
			}
			if (!tokenValue.equals(requestToken)) {
				// 跳转至提示页面，断定为重复提交
				request.getRequestDispatcher(errorPage).forward(request, response);
				return false;
			} else {
				// 替换新的token
				session.setAttribute(ConstantUtils.TOKEN_VALUE,
						session.getId() + String.valueOf(System.currentTimeMillis()));

				return super.preHandle(request, response, handler);
			}
		}

	}

	private String errorPage = ConstantUtils.EMPTY_STRING;

	public void setErrorPage(String errorPage) {
		this.errorPage = errorPage;
	}

	/**
	 * 被拦截的Url
	 */
	private List<String> interceptorUrl = new ArrayList<String>();

	public void setInterceptorUrl(List<String> interceptorUrl) {
		this.interceptorUrl = interceptorUrl;
	}

	/**
	 * 进行当前Url与拦截的Url进行匹配
	 * 
	 * @param url
	 *            当前Url
	 * @return 匹配：True， 不匹配：False
	 */
	private boolean matches(String url, String patternUrl) {
		StringBuffer buff = new StringBuffer();
		buff.append('^');
		buff.append(patternUrl.replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\\\?").replaceAll("\\*", ".*"));
		buff.append('$');
		Pattern pattern = Pattern.compile(buff.toString());
		Matcher matcher = pattern.matcher(url);
		boolean found = matcher.find();
		return found && matcher.group().equals(url);
	}

}
